package first.codeTop.byteDance;

import java.util.HashMap;

/**
 * @ClassName Leetcode3
 * @description:
 * @author: 荣燊
 * @create: 2021-07-23 16:25
 **/
public class Leetcode3 {
    // 无重复字符的最长子串

    /**
     * 测试用例：
     * 1. abba
     */
    public static void main(String[] args) {
        String s = "abba"; // wke
        System.out.println(lengthOfLongestSubstring(s));
    }

    // 滑动窗口
    public static int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) {
            return 0;
        }
        char[] chars = s.toCharArray();
        int max = 0;
        int left = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i=0; i<chars.length; i++) {
            if (map.containsKey(chars[i])) {
                // 对于abba这样的测试用例，遍历到a时，left=2，所以得去最大值
                left = Math.max(left, map.get(chars[i])+1);
            }
            map.put(chars[i], i);
            max = Math.max(max, i-left+1);
        }

        return max;
    }
}
